<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 2018/9/30
 * Time: 16:22
 */

namespace app\admin\controller;
use app\common\model\Banner as BannerModel;


use app\common\validate\BannerValidate;
use app\common\validate\IDMustBePostiveInt;
use think\Exception;
use think\facade\Request;

class Banner extends Common
{
    /**
     * banner列表
     * @return \think\response\Json|\think\response\View
     * @throws \think\exception\DbException
     */
    public function index() {
        if (Request::isAjax()) {
            $data = BannerModel::all(function ($query) {
                $query->order('sort asc, id desc');
            });
            return return_data('banner列表', 0, $data);
        }
        return view();
    }

    /**
     * 保存banner
     * @return BannerModel|array|null|\think\response\Json|\think\response\View
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function save_banner() {
        $id = input('param.id', 0);
        if (request()->isAjax()) {

            $banner_validate = new BannerValidate();
            $banner_validate->goCheck();
            $param = $banner_validate->getDataByRule(input('param.'));
            $data = BannerModel::createOrUpdateBanner($param, $id);
            return $data;
        } else {
            $data = [];
            if ($id > 0) {
                $data = BannerModel::get($id);
            }

            $this->assign('data', $data);

            return view();
        }
    }

    /**
     * 删除banner
     * @return \think\response\Json
     * @throws Exception
     * @throws \think\exception\DbException
     */
    public function delete_banner() {
        (new IDMustBePostiveInt())->goCheck();
        $id = input('param.id');
        $banner = BannerModel::get($id);
        if (!$banner) {
            return return_data('banner不存在');
        }
        try {
            $banner->delete();
            return return_data('删除成功！');
        } catch (Exception $e) {
            return return_data($e->getMessage(), 1);
        }

    }

    /**
     * 修改banner排序
     * @return \think\response\Json
     * @throws Exception
     * @throws \think\exception\DbException
     */
    public function save_sort() {
        (new IDMustBePostiveInt())->goCheck();
        $id = input('param.id');
        $banner = BannerModel::get($id);
        if (!$banner) {
            return return_data('banner不存在');
        }
        try {
            $banner->save([
                'sort' => input('param.sort')
            ]);
            return return_data('修改成功！');
        } catch (Exception $e) {
            return return_data($e->getMessage(), 1);
        }

    }
}